package com.ypj.rpc.utils;

import com.ypj.rpc.entity.RpcRequest;
import com.ypj.rpc.entity.RpcResponse;
import com.ypj.rpc.enumeration.ResponseCode;
import com.ypj.rpc.enumeration.RpcError;
import com.ypj.rpc.exception.RpcException;
import lombok.extern.slf4j.Slf4j;

/**
 * 用于检查请求与响应之间是否匹配
 */
@Slf4j
public class RpcMessageChecker {

    public RpcMessageChecker() {
    }

    public static void check(RpcResponse rpcResponse, RpcRequest rpcRequest){
        if (rpcResponse==null){
            log.error("调用服务失败，serviceName:{}",rpcRequest.getInterfaceName());
            throw new RpcException(RpcError.SERVICE_INVOCATION_FAILURE.getMessage());
        }
        if (!rpcRequest.getRequestId().equals(rpcResponse.getRequestId())){
            log.error("响应与请求不匹配");
            throw new RpcException(RpcError.RESPONSE_NOT_MATCH.getMessage());
        }
        if (rpcResponse.getStatusCode()==null||!rpcResponse.getStatusCode().equals(ResponseCode.SUCCESS.getCode())){
            log.error("调用服务失败,serviceName:{},RpcResponse:{}", rpcRequest.getInterfaceName(), rpcResponse);
            throw new RpcException(RpcError.SERVICE_INVOCATION_FAILURE.getMessage());
        }
    }
}
